 <!--
* description: 计划编辑
* author: wangml
* createdDate: 2020-12-5
-->
<template>
  <section class="cartypeQuery">
    <el-dialog
      id="cartypeq"
      v-dialogDrag
      :title="title"
      :visible.sync="popupsVisible"
      :width="editWidth"
      center
      :append-to-body="true"
      :lock-scroll="true"
      :before-close="handleClose"
    >
      <dialogHeader
        slot="title"
        :title="title"
        :style-type="$store.state.app.dialogType"
      />
      <template v-for="comps in editForms">
        <div :key="comps.tid" class="filter-container filter-params">
          <h3 v-if="comps.title" :style="styleObj">{{ comps.title }}</h3>
          <el-row ref="vailComponentList1" :gutter="26">
            <component
              :is="comp.component"
              v-for="comp in comps.data.filter(o => o.isMust === true)"
              :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
              :key="comp.compKey"
              :validrule="comp.validrule"
              :code-field="comp.codeField"
              :text-field="comp.textField"
              :popups-key="comp.compKey"
              :code="formField[comp.codeField]"
              :disabled="comp.disabled"
              :is-require="comp.isRequire"
              :is-mul="comp.isMul"
              :span="comp.span || 24"
              :label-name="comp.labelName"
              :format="comp.format"
              :lookuptype="comp.lookuptype"
              :data-to-object="comp.dataToObj"
              :date-options-type="comp.dateOptionsType"
              :date-type="comp.dateType"
              :custom-obj="comp.customObj"
              :options="comp.options"
              :o-fields="comp.oFields"
              @changeCode="getComponentCode"
              @focusCode="getFocusCode"
            />
          </el-row>
        </div>
      </template>
      <el-divider />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" icon="iconfont  icon-confirm" @click="save">保存 </el-button>
        <el-button size="mini" type="info" @click="cancel">取消</el-button>
        <el-button size="mini" type="info" @click="clear">清除</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>

import Vue from 'vue'
import { formMixins } from '@/components/mixins/formMixins'
import api from '@/api/planReport'
export default {
  name: 'EditPage',
  components: {
    lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题,
  },
  mixins: [formMixins],
  props: {
    title: { type: String, default: '' },
    popupsVisible: { type: Boolean, default: false },
    editForms: { type: Array, default: () => ([]) },
    editWidth: { type: String, default: '55%' },
    code: { type: String, default: '' },
    comType: { type: String, default: '' },
    codeField: { type: String, default: '' },
    popupsKey: { type: String, default: '' },
    isMul: { type: Boolean, default: true },
    validrule: {
      type: Object,
      default: () => {}
    }
  },
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      // apiStyle: 'restful',
      // ruleSettingShow: false,
      // h3标题行内样式
      tableComponents: [],
      genCodeFiled: null,
      styleObj: { borderLeft: null },
      curPopupsVisible: this.popupsVisible,
      formField: null

    }
  },
  watch: {
    formField: {
      handler(newVal) {
        // console.log(newVal)
      },
      deep: true
    },
    popupsVisible: {
      handler(newVal) {
        if (newVal) {
          const {
            carConfigCode, carColorCode, carIncolorCode,
            optionalPagCode, carSeriesCode, ttCode, carSerId, carConfigId, carIncolorId, carOptionalpagId, carColorId
          } = this.dynamicEditRowData
          // console.log(this.popupsState)
          this.$nextTick(() => {
            const comp = this.$refs['truecompKey2'][0]
            if (this.popupsState === 'edit') {
              comp.innerForm = {
                carSeriesCn: carSerId, ttCode, carSeriesCode,
                carConfigCode, carColorCode, carIncolorCode, optionalPagCode, carConfigId, carIncolorId, carOptionalpagId, carColorId
              }
            } else {
              comp.innerForm = { }
            }
          })
        }
      },
      immediate: true
    }
  },
  created() {
    this.tableComponents = this.editForms.reduce((pre, cur) => [...pre, ...cur.data], [])
    this.genCodeFiled = this.genUtil(this.tableComponents)
    this.formField = this.genCodeFiled()
    this.formField.carSerId = ''
    this.formField.carConfigId = ''
    this.formField.carOptionalpagId = ''
    this.formField.carColorId = ''
    this.formField.carIncolorId = ''
    this.formField.monthPlanId = ''
    // this.formField.makingMonth = ''
    this.formField.ttCode = ''
    this.formField.planStatus = ''
    // this.formField.carIncolorId = ''
  },

  mounted() {
    this.setColor()
  },
  methods: {
    // 保存按钮点击事件
    save() {
      this.$utils.validataMoth(this, 'validpopup')
      // eslint-disable-next-line no-undef
      if (this.valid) {
        const reqData = this.$utils.deepCopy(this.formField)
        reqData['updateControlId'] = this.dynamicEditRowData.updateControlId
        reqData['salesPlanId'] = this.dynamicEditRowData.salesPlanId
        // reqData['carInColorId'] = reqData['carIncolorId']
        // delete reqData.carIncolorId
        this.$requestAPI({
          apiUrl: this.title === '销售计划跟踪'
            ? api.SalePlanTrackingEdit.APIUrl
            : api.update.APIUrl,
          variables: reqData
        }).then(response => {
          if (response.result === '1') {
            this.$message(response.msg)
            this.$parent.$refs['multipleTable'].queryTable(1)
            this.$emit('update:popupsVisible', false)
          }
        }).catch(err => {
          this.$message(err.response.data.msg)
        })
      }
    },
    // 取消按钮点击事件
    cancel() {
      this.handleClose()
    },
    // 清除按钮点击事件
    clear() {
      this.formField.ttCode = ''
      this.formField.planNum = ''
      this.resetIconV()
    },
    // 避免 bug
    onCreated() {
      if (this.formField === null) {
        this.formField = { carBrandCode: '' }
      }
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {}),
    // 设置h3标题颜色
    setColor() {
      const nowSystemColor = this.$store.getters.nowTheme.backgroundColor
      this.styleObj.borderLeft = `5px solid ${nowSystemColor}`
    },
    // 隐藏(重置)验证图标
    resetIconV() {
      this.$nextTick(() => {
        for (const comp in this.$refs) {
          if (comp.includes('true')) {
            this.$refs[comp][0].$children[0].$children[2].iconV = '3'
          }
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.$confirm(`确认关闭？`)
        .then(_ => {
          this.resetIconV()
          this.$emit('update:popupsVisible', false)
          done()
        })
        .catch(_ => {})
    }

  }
}
</script>

<style lang="css" scoped>
  h3 {
    padding-left: 10px;
    text-align: left;
    font-weight: 600;
  }

  h3 button.el-button {
    float: right;
    margin-right: 10px;
  }
  >>> div.el-col.el-col-24 {
    margin-bottom: 10px;
  }

  .dialog-footer {
    float: right;
  }
  >>>.el-dialog__footer {
    overflow: hidden;
    padding: 10px 24px;
  }
</style>
